package com.mike.filter;

import com.mike.service.UserServiceFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description
 * @Date 2021/11/30 15:49
 * @Created by mike
 */
@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {

    @Autowired
    private UserServiceFeignClient userClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        String path = request.getPath().toString();
        if (path.startsWith("/api/user") || path.startsWith("/api/code")){
            return chain.filter(exchange);
        }
        if (cookies.containsKey("token")){
            HttpCookie httpCookie = cookies.get("token").get(0);
            String token = httpCookie.getValue();
            // TODO 根据token查询邮箱
            String email = userClient.getEmailByToken(token);
            if (StringUtils.isEmpty(email)){
                return toLogin(response);
            }
        }else {
            return toLogin(response);
        }
        return chain.filter(exchange);
    }

    private Mono<Void> toLogin(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
        response.getHeaders().add("Location","/login.html");
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
